﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;

namespace huqiang.Framework.Http
{
    public class HWebClient:WebClient
    {
        int _timeOut=8000;
        public int TimeOut { 
            get => _timeOut; 
            set 
            {
                if (value < 1000)
                    value = 1000;
                _timeOut = value;
            }
        }
        public int StartPos =0;
        HttpWebResponse _response;
        HttpStatusCode statusCode;
        public bool Done;
       
        public HttpStatusCode StatusCode { get {
                if (_response != null)
                    return _response.StatusCode;
                return statusCode;
            } }
        protected override WebRequest GetWebRequest(Uri address)
        {
            statusCode = HttpStatusCode.Unused;
            HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
            request.Timeout = _timeOut;
            request.ReadWriteTimeout = _timeOut;
            if(StartPos>0)
            { 
               request.AddRange(StartPos);//设置Range值，断点续传                
            }
            return request;
        }
        protected override WebResponse GetWebResponse(WebRequest request)
        {
            WebResponse response = base.GetWebResponse(request);
            _response = response as HttpWebResponse;
            return response;
        }
        protected override WebResponse GetWebResponse(WebRequest request,IAsyncResult result)
        {
            WebResponse response = base.GetWebResponse(request,result);
            _response = response as HttpWebResponse;
            return response;
        }
        public long GetFileLength(string url)
        {
            return GetFileLength(new Uri(url));
        }
        public long GetFileLength(Uri uri)
        {
            var request = GetWebRequest(uri);
            var response = GetWebResponse(request);
            return response.ContentLength;
        }
        protected override void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
        {
            base.OnDownloadProgressChanged(e);
            //e.BytesReceived;
        }
        protected override void OnDownloadFileCompleted(AsyncCompletedEventArgs e)
        {
            base.OnDownloadFileCompleted(e);
            if (_response != null)
                statusCode = _response.StatusCode;
            Done = true;
        }
    }
}
